package com.mobilezu.mobile.pushserver.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import com.mobilezu.mobile.pushserver.model.PushUser;
import com.mobilezu.mobile.pushserver.service.PushUserService;
import com.mobilezu.mobile.pushserver.service.ServiceManager;
import com.mobilezu.mobile.pushserver.service.UserExistsException;
import com.mobilezu.mobile.pushserver.util.Config;
import com.mobilezu.mobile.pushserver.util.Constants;
import com.mobilezu.mobile.pushserver.util.DBUtil;
import com.mobilezu.mobile.pushserver.xmpp.presence.PresenceManager;
import com.mobilezu.mobile.pushserver.xmpp.push.NotificationManager;
import com.opensymphony.xwork2.ActionSupport;
/**
 *客户端服务 
 * @author liruwang
 */
public class ClientAction extends ActionSupport {
	
	private static final long serialVersionUID = -36741751955624114L;
	protected final Log logger = LogFactory.getLog(getClass());
	private PushUserService pushUserService;

	public ClientAction() {

		pushUserService = ServiceManager.getPushUserService();
	}
	
	/**
	 * 客户端登录
	 * @return 返回消息码
	 */
	public String doLogin() throws ServletException, IOException{
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		PrintWriter out = response.getWriter();
		String returnStr = "2";

		PushUser user = pushUserService.getPushUserByUsername(username);
		if (user != null && user.getPassword().equals(password)) {
			returnStr = "1";
		} else {
			returnStr = "0";
		}
		out.print(returnStr);
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 用户注册方法
	 * @return 返回操作码
	 */
	public String doRegster()  throws ServletException, IOException{
		//执行用户注册
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();
		String returnStr = "2";
		String action = request.getParameter("action");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String time = Constants.getNowBeiJingTime();

		if (action != null && action.equals("reg")) {
			PushUser pushUser = new PushUser(username, password, name, email,
					time, time);
			try {
				pushUserService.savePushUser(pushUser);
				returnStr = "1";
			} catch (UserExistsException e) {
				returnStr = "0";
			} finally {
				out.print(returnStr);
				out.flush();
				out.close();
			}
		} else if (action != null && action.equals("modify")) {
			Connection con = DBUtil.openConn();
			try {
				String sqlUpdateUser = "update tb_push_user set password = '"
						+ password + "',name = '" + name + "',updated_date = '"
						+ time + "',email = '" + email + "' where username = '"
						+ username + "'";
				PreparedStatement ps = con.prepareStatement(sqlUpdateUser);
				if (ps.executeUpdate() > 0) {
					returnStr = "1";
				} else {
					returnStr = "0";
				}
			} catch (SQLException e) {
				returnStr = "2";
				e.printStackTrace();
			} finally {
				DBUtil.closeConn(con);
				out.print(returnStr);
				out.flush();
				out.close();
			}

		}
		
		return null;
	}
	
	/**
	 * 获取所有用户方法
	 * @return 返回操作码
	 */
	public String doGetAllUser() throws ServletException, IOException{
		//执行获取所有用户
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String returnStr = "2";
		try {
			String fromMyPushClient = request.getParameter("fromMyPushClient");
			String returnUsernameStr = "";
			String returnNameStr = "";
			PresenceManager presenceManager = new PresenceManager();
			List<PushUser> userList = pushUserService.getPushUsers();

			if ("true".equals(fromMyPushClient) && userList != null
					&& userList.size() > 0) {
				for (PushUser user : userList) {
					if (presenceManager.isAvailable(user)) {
						returnUsernameStr = returnUsernameStr + "@"
								+ user.getUsername() + ",";
					} else {
						returnUsernameStr = returnUsernameStr
								+ user.getUsername() + ",";
					}
					if (user.getName() != null && !user.getName().equals("")) {
						returnNameStr = returnNameStr + user.getName() + ",";
					} else {
						returnNameStr = returnNameStr + user.getUsername()
								+ ",";
					}
				}
				returnUsernameStr = returnUsernameStr.trim();
				returnUsernameStr = returnUsernameStr.substring(0,
						returnUsernameStr.length() - 1);
				returnNameStr = returnNameStr.trim();
				returnNameStr = returnNameStr.substring(0,
						returnNameStr.length() - 1);
				returnStr = returnUsernameStr + ";" + returnNameStr;
			} else {
				returnStr = "0";
			}
		} catch (Exception e) {
			returnStr = "2";
		} finally {
			out.print(returnStr);
			out.flush();
			out.close();
		}
		return null;
	}
	
	/**
	 * 根据DataID获取图片资源方法
	 * @return 返回操作码
	 */
	public String doGetImageByDataId(){
		//获取图片对象
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		Connection con = DBUtil.openConn();
		try {
			Statement stmt = con.createStatement();
			ResultSet rs = null;
			String dataId = request.getParameter("dataId");
			String sql = "select image from tb_push_image where image is not null and data_id='"
					+ dataId + "'";
			rs = stmt.executeQuery(sql);
			if (rs.next()) {
				byte[] bs = rs.getBytes("image");
				response.setContentType("image/jpeg");
				OutputStream outs = response.getOutputStream();
				outs.write(bs);
				outs.flush();
				outs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConn(con);
		}
		return null;
	}
	
	/**
	 * 获取注册信息方法
	 * @return 返回操作码
	 */
	public String doGetRegsterInfo() throws ServletException, IOException{
		//获取注册信息方法
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String returnStr = "2";
		String username = request.getParameter("username");
		PushUser pushUser = pushUserService.getPushUserByUsername(username);
		if (pushUser != null) {
			returnStr = pushUser.getPassword() + "#" + pushUser.getName() + "#"
					+ pushUser.getEmail();
		}
		out.print(returnStr);
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 上传图片方法
	 * @return 返回操作码
	 */
	public String doSendImage() throws ServletException, IOException{
		//发送图片
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		NotificationManager notificationManager = new NotificationManager();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String outStr = "2";
		
		String usernames = new String(request.getParameter("recvUsername")
				.getBytes("iso-8859-1"), "UTF-8");
		String senderUsername = new String(request.getParameter(
				"senderUsername").getBytes("iso-8859-1"), "UTF-8");
		String sendName = pushUserService.getPushUserByUsername(senderUsername)
				.getName();
		String message = Constants.subString(
				new String(request.getParameter("message").getBytes(
						"iso-8859-1"), "UTF-8"), 1000);
		String gps = new String(request.getParameter("gps").getBytes(
				"iso-8859-1"), "UTF-8");
		String uri = Constants.subString(new String(request.getParameter("uri")
				.getBytes("iso-8859-1"), "UTF-8"), 500);
		String time = new String(request.getParameter("time").getBytes(
				"iso-8859-1"), "UTF-8");
		String apiKey = Config.getString("apiKey", "");
		String dataId = Constants.getDataId();

		InputStream inputStream = null;
		FileItem fileItem = null;

		DiskFileUpload diskFileUpload = new DiskFileUpload();

		diskFileUpload.setSizeMax(10 * 1024 * 1024);
		diskFileUpload.setSizeThreshold(4096);

		int index = 0;
		List<?> fileItems = null;
		try {
			fileItems = diskFileUpload.parseRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Iterator<?> iter = fileItems.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (!item.isFormField()) {
				fileItem = item;
				index++;
				try {
					inputStream = (InputStream) item.getInputStream();
				} catch (Exception ex) {
				}
			} else {
				item.getString();
			}
		}
		Connection con = DBUtil.openConn();
		try {
			String sqlInsertImage = "insert into tb_push_image(data_id,image) values('"
					+ dataId + "',? )";
			PreparedStatement ps = con.prepareStatement(sqlInsertImage);
			if (inputStream == null) {
				throw new Exception();
			} else {
				//ps.setBinaryStream(1, inputStream, (int) fileItem.getSize());
				ps.setBlob(1, inputStream, (int) fileItem.getSize());
			}
			if (ps.executeUpdate() > 0) {
				outStr = "1";
				notificationManager.clientSendToSomeUsers(dataId, "1", gps,
						apiKey, senderUsername, sendName, usernames, message,
						uri, time);
			} else {
				outStr = "0";
			}
		} catch (Exception e) {
			e.printStackTrace();
			outStr = "2";
		} finally {
			try {
				con.close();
				out.print(outStr);
				out.flush();
				out.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
	
	/**
	 * 执行发送消息方法
	 * @return 返回操作码
	 */
	public String doSend()  throws ServletException, IOException{
		//TODO 发送消息
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		NotificationManager notificationManager = new NotificationManager();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String returnStr = "2";
		try {
			String usernames = request.getParameter("recvUsername");
			String senderUsername = request.getParameter("senderUsername");
			PushUser senderUser= pushUserService.getPushUserByUsername(senderUsername);
			if(senderUser!=null){
				String sendName =senderUser.getName();
				String message = Constants.subString(request.getParameter("message"),1000);
				String gps = request.getParameter("gps");
				String uri = Constants.subString(request.getParameter("uri"), 500);
				String time = request.getParameter("time");
				String apiKey = Config.getString("apiKey", "");
				notificationManager.clientSendToSomeUsers(Constants.getDataId(),
						"0", gps, apiKey, senderUsername, sendName, usernames,
						message, uri, time);
				returnStr = "1";
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "2";
		} finally {
			out.print(returnStr);
			out.flush();
			out.close();
		}
		return null;
	}
	
	/**
	 * 执行更新方法
	 * @return 返回操作码
	 */
	public String doUpgrade()  throws ServletException, IOException{
		//执行更新
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		
		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String returnStr = "0";
		try {
			String clientVersion = request.getParameter("version");
			logger.debug("clientVersion=" + clientVersion);
			if (!clientVersion.equals(Constants.client_version)) {
				returnStr = Constants.client_download_url;
			}
		} catch (Exception e) {
			returnStr = "2";
		}
		out.print(returnStr);
		out.flush();
		out.close();
		return null;
	}
	
	
}
